<template>
  <div>
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        tooltip-effect="dark"
        row-key="ID"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />

        <!-- 标题列 -->
        <el-table-column align="left" label="标题" prop="title" width="150" />
        <el-table-column align="left" label="需求" prop="require" width="200" />
        <!-- 需求方列 -->
        <el-table-column
          align="left"
          label="需求方"
          prop="publisher"
          width="150"
        />
        <!-- 候选技术方列 -->
        <el-table-column
          align="left"
          label="候选技术方"
          prop="candidates"
          width="200"
        />

        <!-- 价格列 -->
        <el-table-column align="left" label="价格" width="150">
          <template #default="scope">
            <div>{{ scope.row.min_price }} ~ {{ scope.row.max_price }} 元</div>
          </template>
        </el-table-column>

        <!-- 需求列 -->
        <el-table-column align="left" label="审核通过时间" width="150">
          <template #default="scope">
            <div>{{ new Date(scope.row.updated_at).toLocaleString() }}</div>
          </template>
        </el-table-column>
        <!-- 时间要求列 -->
        <el-table-column
          align="left"
          label="其他要求"
          prop="other"
          width="180"
        />

        <!-- 操作列 -->
        <el-table-column align="right" label="操作" min-width="200">
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              link
              icon="edit"
              @click.stop="openEditForm(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 编辑抽屉 -->
    <el-drawer
      v-model="drawerFormVisible"
      :before-close="closeDrawer"
      :show-close="false"
      size="30%"
      direction="rtl"
    >
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">订单处理选项</span>
          <el-button icon="close" @click="closeDrawer" circle></el-button>
        </div>
      </template>

      <el-form :model="form" label-width="120px">
        <!-- 候选技术方选择框 -->
        <el-form-item label="候选技术方">
          <el-select
            v-model="form.candidateTech"
            placeholder="请选择候选技术方"
          >
            <el-option
              v-for="candidate in candidateOptions"
              :key="candidate.id"
              :label="candidate.nickname"
              :value="candidate.id"
            />
          </el-select>
        </el-form-item>

        <!-- 成交价格 -->
        <el-form-item label="成交价格">
          <el-input
            v-model="form.price"
            type="number"
            autocomplete="off"
            placeholder="请输入成交价格"
          />
        </el-form-item>
      </el-form>

      <div class="flex justify-end mt-4">
        <el-button @click="closeDrawer" size="small">取消</el-button>
        <el-button type="primary" @click="confirmEdit" size="small"
          >确认</el-button
        >
      </div>
    </el-drawer>
    <el-dialog
      v-model="dialogFormVisible"
      width="50%"
      :before-close="closeDialog"
    >
      <template #title>
        <div>订单详情</div>
      </template>

      <!-- 子组件 OrderDetail 传递 orderId -->
      <OrderDetail v-if="dialogFormVisible" :orderId="currentOrderId" />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { getOrderList, updateUnFinishOrder } from "@/api/order";
import OrderDetail from "@/components/OrderDetails.vue";

import { useRouter } from "vue-router";
const router = useRouter();
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const candidateOptions = ref([]); // 候选人选项列表
const form = ref({
  candidateTech: "", // 选中的候选技术方
  price: 0, // 成交价格
  row: {}, // 当前行数据
});
const dialogFormVisible = ref(false);
const currentOrderId = ref(0);

// 处理点击行跳转
const handleRowClick = (row, column, event) => {
  // 检查点击事件是否发生在操作列
  if (event.target.closest(".el-button")) return;

  currentOrderId.value = row.order_id;
  dialogFormVisible.value = true; // 跳转到 OrderDetails 页面，并传递 id
};

const closeDialog = () => {
  dialogFormVisible.value = false;
};

// 获取表格数据
const getTableData = async () => {
  tableData.value = [];
  const table = await getOrderList({
    page: page.value,
    pageSize: pageSize.value,
    type: 2,
  });
  if (table.code === 0) {
    table.data.list.forEach((item) => {
      item.candidateDeatils = item.candidates;
      let candidates = [];
      if (!item.candidates || item.candidates.length === 0) {
        item.candidates = "暂无候选人";
      } else {
        item.candidates.forEach((c) => {
          candidates.push(c.nickname + "(" + c.phone + ")");
        });
        item.candidates = candidates.join(",");
      }
    });
    tableData.value = table.data.list;
    total.value = table.data.total;
    page.value = table.data.page;
    pageSize.value = table.data.pageSize;
  }
};

getTableData();

// 抽屉相关
const drawerFormVisible = ref(false);

// 打开编辑表单
const openEditForm = (row) => {
  drawerFormVisible.value = true; // 打开抽屉
  form.value.price = ""; // 清空价格字段
  form.value.candidateTech = ""; // 清空候选技术方选择框
  form.value.row = row;
  candidateOptions.value = row.candidateDeatils.map((candidate) => ({
    id: candidate.id,
    nickname: candidate.nickname + "(" + candidate.phone + ")",
  })); // 将候选人信息转换为选项列表
};

// 关闭抽屉
const closeDrawer = () => {
  drawerFormVisible.value = false;
};

// 确认编辑
const confirmEdit = async () => {
  const { min_price, max_price } = form.value.row;
  const price = Number(form.value.price);

  // 验证价格是否在 min_price 和 max_price 区间内
  if (price < min_price || price > max_price) {
    ElMessage({
      type: "warning",
      message: `成交价格必须在 ${min_price} ~ ${max_price} 元之间`,
    });
    return; // 中断提交操作
  }

  const res = await updateUnFinishOrder({
    orderId: form.value.row.order_id,
    userId: form.value.candidateTech,
    price,
  });

  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "订单匹配处理成功",
    });
    getTableData();
    closeDrawer();
  }
};
</script>
